from django.test import TestCase
from django.urls import reverse

from .models import Book


def insert_book_records(n):
    for i in range(n):
        Book.objects.create(
            name='book%s' % i,
            author='author%s' % i,
            price=i+1,
            year=2018
        )


class BookIndexViewTests(TestCase):

    def test_limited_number_of_books(self):
        """当指定了查询条目时，就是显示指定数量的记录"""
        num = 3
        insert_book_records(num + 1)
        r = self.client.get(reverse('app1:index', kwargs={'num': num}))
        self.assertEqual(r.context['total'], num)

    def test_not_specify_number_of_books(self):
        """当不指定查询条目时，就显示所有记录"""
        num = 3
        insert_book_records(num)
        r = self.client.get(reverse('app1:index'))
        self.assertEqual(r.context['total'], num)


class BookDetailViewTests(TestCase):

    def test_invalid_pk_404(self):
        """当pk不存在时，status_code应该是404"""
        insert_book_records(3)
        r = self.client.get(reverse('app1:detail', kwargs={'pk': 12345}))
        self.assertEqual(r.status_code, 404)
